package com.heima.user.service.impl;


import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.heima.common.constants.message.FollowBehaviorConstants;
import com.heima.common.exception.CustomException;
import com.heima.feigns.article.ArticleFeign;
import com.heima.model.article.pojos.ApAuthor;
import com.heima.model.behavior.dtos.FollowBehaviorDto;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.user.dtos.UserRelationDto;
import com.heima.model.user.pojos.ApUser;
import com.heima.model.user.pojos.ApUserFan;
import com.heima.model.user.pojos.ApUserFollow;
import com.heima.model.utils.threadlocal.AppThreadLocalUtils;
import com.heima.user.mapper.ApUserFanMapper;
import com.heima.user.mapper.ApUserFollowMapper;
import com.heima.user.service.ApUserRelationService;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Date;

@Service
public class ApUserRelationServiceimpl implements ApUserRelationService {

    @Resource
    ArticleFeign articleFeign;

    @Override
    public ResponseResult follow(UserRelationDto dto) {
        //参数校验
        if (dto == null) {
            throw new CustomException(AppHttpCodeEnum.PARAM_REQUIRE);
        }

        //判断作者是否存在
        if (dto.getAuthorId() == null) {
            throw new CustomException(AppHttpCodeEnum.PARAM_REQUIRE, "作者id不存在");
        }

        ApAuthor author = articleFeign.selectById(dto.getAuthorId());

        if (author == null) {
            throw new CustomException(AppHttpCodeEnum.DATA_NOT_EXIST, "作者信息不存在");
        }

        //判断用户是否登录
        ApUser user = AppThreadLocalUtils.getUser();
        if (user == null) {
            throw new CustomException(AppHttpCodeEnum.NEED_LOGIN);
        }

        //判断是取消还是关注
        if (dto.getOperation() == 0) { //关注
            return followByUserId(user, author,dto.getArticleId());

        } else {  //取消
            return followCancelByUserId(user, author);
        }

    }

    @Resource
    ApUserFanMapper apUserFanMapper;

    @Resource
    ApUserFollowMapper apUserFollowMapper;

    private ResponseResult followCancelByUserId(ApUser apUser, ApAuthor author) {
        //参数校验
        if (apUser.getId() == null || author.getId() == null) {
            throw new CustomException(AppHttpCodeEnum.PARAM_INVALID);
        }
        //查询关注表和粉丝表数据是否存在

        ApUserFan userFan = apUserFanMapper.selectOne(Wrappers.<ApUserFan>lambdaQuery().eq(ApUserFan::getFansId, apUser.getId())
                .eq(ApUserFan::getUserId, author.getId())
        );
        if (userFan == null) {
            throw new CustomException(AppHttpCodeEnum.DATA_NOT_EXIST, "粉丝表数据不存在");
        }

        ApUserFollow userFollow = apUserFollowMapper.selectOne(Wrappers.<ApUserFollow>lambdaQuery().eq(ApUserFollow::getUserId, apUser.getId())
                .eq(ApUserFollow::getFollowId, author.getId())
        );

        if (userFollow == null) {
            throw new CustomException(AppHttpCodeEnum.DATA_NOT_EXIST, "关注表数据不存在");
        }

        //删除关注表和粉丝表数据
        apUserFanMapper.delete(Wrappers.<ApUserFan>lambdaQuery().eq(ApUserFan::getFansId, apUser.getId())
                .eq(ApUserFan::getUserId, author.getId()));

        apUserFollowMapper.delete(Wrappers.<ApUserFollow>lambdaQuery().eq(ApUserFollow::getUserId, apUser.getId())
                .eq(ApUserFollow::getFollowId, author.getId()));


        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }


    @Resource
    KafkaTemplate kafkaTemplate;

    private ResponseResult followByUserId(ApUser apUser, ApAuthor author, Long articleId) {
        //参数校验
        if (apUser.getId() == null || author.getId() == null) {
            throw new CustomException(AppHttpCodeEnum.PARAM_INVALID);
        }

        if (apUser.getId().equals(author.getId())) {
            throw new CustomException(AppHttpCodeEnum.DATA_EXIST, "无需关注自己");
        }

        //封装关注表数据
        ApUserFollow userFollow = new ApUserFollow();
        userFollow.setCreatedTime(new Date());
        userFollow.setFollowId(author.getId());
        userFollow.setFollowName(apUser.getName());
        userFollow.setLevel((short) 1);
        userFollow.setIsNotice(true);
        userFollow.setUserId(apUser.getId());

        //添加关注表数据
        apUserFollowMapper.insert(userFollow);

        //封装粉丝表数据
        ApUserFan userFan = new ApUserFan();
        userFan.setUserId(author.getId());
        userFan.setCreatedTime(new Date());
        userFan.setLevel((short) 0);
        userFan.setIsShieldComment(false);
        userFan.setIsShieldLetter(false);
        userFan.setIsDisplay(true);
        userFan.setFansId(Long.valueOf(apUser.getId()));
        userFan.setFansName(apUser.getName());

        //添加粉丝表数据
        apUserFanMapper.insert(userFan);

        //发送通知到用户行为微服务
        FollowBehaviorDto dto = new FollowBehaviorDto();
        dto.setArticleId(articleId);
        dto.setFollowId(author.getId());
        dto.setUserId(apUser.getId());

        kafkaTemplate.send(FollowBehaviorConstants.FOLLOW_BEHAVIOR_TOPIC, JSON.toJSONString(dto));
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }
}
